package com.rongke.biz.service.impl;

import java.util.Date;
import java.util.UUID;

import jodd.util.StringUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rongke.biz.service.UserManager;
import com.rongke.commons.JsonResp;
import com.rongke.model.User;
import com.rongke.service.UserService;
import com.rongke.utils.Md5;
import com.rongke.utils.UserIdGenerator;

/**
 * 用户业务层
 * 
 * @author xiaosen.jxs
 * @version $Id: UserManagerImpl.java, v 0.1 2017年10月11日 下午7:09:46 xiaosen.jxs Exp $
 */
@Service
public class UserManagerImpl implements UserManager {

    @Autowired
    private UserService userService;

    @Override
    public User selectOrAddUser(String mobileNo) {
        if (StringUtil.isEmpty(mobileNo)) {
            return null;
        }

        User user = userService.selectByPhone(mobileNo);
        if (null != user) {
            return user;
        }

        user = new User();
        String userId = UserIdGenerator.getNewUserId();
        user.setUserId(userId);
        user.setPhone(mobileNo);

        String newToken = UUID.randomUUID().toString();
        newToken = newToken.replaceAll("-", "");
        String md5Token = Md5.md5Encode(newToken);
        user.setToken(md5Token);
        user.setGmtLogin(new Date());
        user.setAlias(mobileNo);// 注册时，用手机号代替别名
        userService.insert(user);

        return user;
    }

    @Override
    public User selectByPhone(String phone) {
        if (StringUtil.isEmpty(phone)) {
            return null;
        }

        return userService.selectByPhone(phone);
    }
}